package com.agnes.network.interceptor;

import android.content.Context;

import com.agnes.network.util.NetUtils;
import com.orhanobut.logger.Logger;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * Desc:   缓存拦截器，保存缓存的方法
 * Creator ling
 * Date:   2017/9/14 0014 14:12
 */

public class CacheInterceptor implements Interceptor {

    private final String TAG = this.getClass().getName();

    private Context context;

    public CacheInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!NetUtils.isConnected(context)) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }

        Response originalResponse = chain.proceed(request);
        if (NetUtils.isConnected(context)) {
            // 在线缓存
            String cacheControl = request.cacheControl().toString();
            Logger.d(TAG + "在线缓存60s内可读取" + cacheControl);
            int maxAge = 60; // 6s内可读取
            return originalResponse.newBuilder()
                .header("Cache-Control", "public, max-age=" + maxAge)
                .removeHeader("Pragma")
                .build();
        } else {
            // 离线缓存
            Logger.d(TAG + "离线时缓存时间设置");
            int maxStale = 4 * 24 * 60 * 60;
            return originalResponse.newBuilder()
                // 这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                .removeHeader("Pragma")
                .build();
        }
    }
}
